from sqlalchemy import Column, Integer, String, Text, DateTime, ForeignKey, Enum, JSON
from sqlalchemy.orm import relationship
from sqlalchemy.sql import func
import enum
from app.core.database import Base


class TaskStatus(str, enum.Enum):
    """任务状态枚举"""
    PENDING = "pending"        # 等待中
    RUNNING = "running"        # 执行中
    WAITING = "waiting"        # 等待外部API结果
    COMPLETED = "completed"    # 已完成
    FAILED = "failed"          # 失败
    CANCELLED = "cancelled"    # 已取消


class StepStatus(str, enum.Enum):
    """步骤状态枚举"""
    PENDING = "pending"
    RUNNING = "running"
    WAITING = "waiting"
    COMPLETED = "completed"
    FAILED = "failed"
    SKIPPED = "skipped"


class AIWorkflow(Base):
    """AI工作流主任务表"""
    __tablename__ = "ai_workflows"
    
    id = Column(Integer, primary_key=True, index=True)
    user_id = Column(Integer, ForeignKey("users.id"), nullable=False, index=True)
    
    # 任务基本信息
    task_name = Column(String(200), nullable=False, comment="任务名称")
    status = Column(Enum(TaskStatus), default=TaskStatus.PENDING, nullable=False, index=True)
    current_step = Column(String(50), comment="当前执行步骤")
    progress = Column(Integer, default=0, comment="进度百分比 0-100")
    
    # 输入输出数据
    input_data = Column(JSON, comment="输入数据")
    result_data = Column(JSON, comment="最终结果数据")
    
    # 新增字段
    task_config = Column(JSON, comment="任务配置参数")
    execution_summary = Column(JSON, comment="执行摘要统计")
    expected_outputs = Column(JSON, comment="预期输出数量")
    
    # 错误处理
    error_message = Column(Text, comment="错误信息")
    retry_count = Column(Integer, default=0, comment="重试次数")
    
    # 时间戳
    created_at = Column(DateTime(timezone=True), server_default=func.now(), nullable=False)
    updated_at = Column(DateTime(timezone=True), server_default=func.now(), onupdate=func.now(), nullable=False)
    started_at = Column(DateTime(timezone=True), comment="开始执行时间")
    completed_at = Column(DateTime(timezone=True), comment="完成时间")
    
    # 关联关系
    user = relationship("User", back_populates="ai_workflows")
    steps = relationship("WorkflowStep", back_populates="workflow", cascade="all, delete-orphan")


class WorkflowStep(Base):
    """工作流步骤表"""
    __tablename__ = "workflow_steps"
    
    id = Column(Integer, primary_key=True, index=True)
    workflow_id = Column(Integer, ForeignKey("ai_workflows.id"), nullable=False, index=True)
    
    # 步骤信息
    step_name = Column(String(100), nullable=False, comment="步骤名称")
    step_order = Column(Integer, nullable=False, comment="执行顺序")
    status = Column(Enum(StepStatus), default=StepStatus.PENDING, nullable=False)
    
    # 外部API相关
    external_task_id = Column(String(200), comment="外部API任务ID")
    external_conversation_id = Column(String(200), comment="外部API对话ID")
    api_provider = Column(String(50), comment="API提供商 coze/midjourney/flux等")
    
    # 数据
    input_data = Column(JSON, comment="步骤输入数据")
    output_data = Column(JSON, comment="步骤输出数据")
    
    # 错误处理
    error_message = Column(Text, comment="错误信息")
    retry_count = Column(Integer, default=0, comment="重试次数")
    
    # 时间戳
    created_at = Column(DateTime(timezone=True), server_default=func.now(), nullable=False)
    updated_at = Column(DateTime(timezone=True), server_default=func.now(), onupdate=func.now(), nullable=False)
    started_at = Column(DateTime(timezone=True), comment="开始执行时间")
    completed_at = Column(DateTime(timezone=True), comment="完成时间")
    
    # 关联关系
    workflow = relationship("AIWorkflow", back_populates="steps")


class ErrorHistory(Base):
    """错误历史记录表"""
    __tablename__ = "error_histories"
    
    id = Column(Integer, primary_key=True, index=True)
    user_id = Column(Integer, ForeignKey("users.id"), nullable=False, index=True)
    workflow_id = Column(Integer, ForeignKey("ai_workflows.id"), nullable=True, index=True)
    step_id = Column(Integer, ForeignKey("workflow_steps.id"), nullable=True, index=True)
    
    # 错误信息
    error_type = Column(String(100), comment="错误类型")
    error_message = Column(Text, nullable=False, comment="错误详情")
    api_provider = Column(String(50), comment="API提供商")
    
    # 用户信息
    user_name = Column(String(100), comment="用户名")
    
    # 时间戳
    created_at = Column(DateTime(timezone=True), server_default=func.now(), nullable=False)
    
    # 关联关系
    user = relationship("User")
    workflow = relationship("AIWorkflow")
    step = relationship("WorkflowStep")